<!-- 电站报表 -->
<template>
  <div class="content">
    <h4 id="title">{{ $t('licence.inv_Title') }}</h4>
    <!-- 标题 -->
    <div class="title">
      <div class="time-box">
        <!-- 年月日选择 --><!-- 选择查询 -->
        <el-date-picker v-model="timeValue" format="YYYY/MM/DD" value-format="YYYY-MM-DD"
         type="daterange" range-separator="-" :start-placeholder="$t('licence.use_kaishi')"
          :end-placeholder="$t('licence.use_jieshu')" :picker-options="pickerOptions">
        </el-date-picker>
        <el-button @click="getStationOverview" type="primary" style="margin: 0 20px">{{ $t('licence.fau_Thequery') }}</el-button>
      </div>
      <!-- 导出 -->
      <div style="display: flex">
        <div class="export" @click="ExportPDF()">
          {{ $t('licence.sta_exportPDF') }}
        </div>
        <div class="export" @click="ExportExl()">
          {{ $t('licence.sta_exportExl') }}
        </div>
      </div>
    </div>
    <!-- 电站概览 -->
    <div ref="divExport">
      <h4 class="stationName">
        {{ powerStation.stationName }}({{ timeValue[0] }} ~ {{ timeValue[1] }})
      </h4>
      <div class="table" style="width: 100%">
        <el-table :data="tableData" :span-method="objectSpanMethod" border style="width: 100%">
          <el-table-column align="center" prop="stationName" label="电站名称"></el-table-column>
          <el-table-column align="center" prop="day" label="时间">
          </el-table-column>
          <el-table-column align="center" prop="electricity" label="日发电量（kWh）"></el-table-column>
          <el-table-column align="center" prop="equivalentHours" label="等效小时数（发电量/装机功率）h"></el-table-column>
        </el-table>
      </div>
      <!-- 数据曲线图 -->

      <div id="echarts" v-loading="loading" ref="divExportExl">
        <!-- 日发电量柱状图 -->
        <h4 id="title">日发电量</h4>
        <div id="DailyElectricity"></div>
        <h4 id="title">总等效小时</h4>
        <div id="equivalent"></div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts" name="Data1">
import * as echarts from "echarts";
import { getStationOverviews, getAgentExp } from "@/api/monitor/diagram";
import { printPdf } from "@/utils/html2canvas";
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
import html2canvas from "html2canvas";
    const onday = ref('')
    const pickerOptions = ref({
      onPick: (time:any) => {
        if (time.minDate && !time.maxDate) {
          onday.value = time.minDate;
        }
        if (time.maxDate) {
          onday.value = "";
        }
        // 配置格式
        const end = new Date();
        const start = new Date();
        start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
        time.$emit('pick', [start, end]);
      },
      disabledDate: (time:any) => {
        let timeone = onday.value;
        let secondNum = 60 * 60 * 24 * 6 * 1000;
        if (onday.value != "") {
          return (
            new Date(timeone).getTime() + secondNum < time.getTime() ||
            time.getTime() > Date.now() ||
            new Date(timeone).getTime() - secondNum > time.getTime()
          );
        } else {
          return time.getTime() > Date.now();
        }
      },
    })
    //=============
    const powerStation= ref({
      id:-1,
      stationName:''
    }) //获取保存电站信息
    // 时间选择器
    const getNowTime = () => {
      const start = new Date(new Date().getTime() - 3600 * 1000 * 24 * 7)
        .toISOString()
        .substring(0, 10)
        .split(".")[0]; //默认开始时间7天前
      const end = new Date(new Date().getTime() - 3600 * 1000 * 24)
        .toISOString()
        .substring(0, 10)
        .split(".")[0]; //默认结束时间1天前
        return [start, end];
    }
    const timeValue = ref<any[]>([]) //日期选择
    const lang = ref(0)
    const loading = ref(false)
    // 电站概览
    const tableData = ref([])
    const divExport = ref()
    const divExportExl = ref()
    // const imagesBase64 = ref([]) //图表转换
    import { ElLoading, type TableColumnCtx } from 'element-plus'
    interface User {
      id: string
      name: string
      amount1: string
      amount2: string
      amount3: number
    }
    interface SpanMethodProps {
      row: User
      column: TableColumnCtx<User>
      rowIndex: number
      columnIndex: number
    }
    // 默认接受四个值 { 当前行的值, 当前列的值, 行的下标, 列的下标 }
    const objectSpanMethod = ({ row, column, rowIndex, columnIndex }:SpanMethodProps) => {
      let data = tableData.value; //拿到当前table中数据
      let cellValue = row[column.property]; //当前位置的值
      let noSortArr = ["day", "electricity", "equivalentHours"]; //不需要合并的字段（不进行合并行的prop）
      if (cellValue && !noSortArr.includes(column.property)) {
        let prevRow = data[rowIndex - 1]; //获取到上一条数据
        let nextRow = data[rowIndex + 1]; //下一条数据
        if (prevRow && prevRow[column.property] === cellValue) {
          //当有上一条数据，并且和当前值相等时
          return { rowspan: 0, colspan: 0 };
        } else {
          let countRowspan = 1;
          while (nextRow && nextRow[column.property] === cellValue) {
            //当有下一条数据并且和当前值相等时,获取新的下一条
            nextRow = data[++countRowspan + rowIndex];
          }
          if (countRowspan > 1) {
            return { rowspan: countRowspan, colspan: 1 };
          }
        }
      }
    }
    // 日发电量柱状图
    const getDailyElectricity = (data:any)=> {
      const myChart = echarts.init(document.getElementById("DailyElectricity") as HTMLElement)as echarts.ECharts;
      myChart.setOption({
        // 悬浮提示
        tooltip: {
          show: true,
          trigger: "axis",
          backgroundColor: "#656565",
          textStyle: { color: "#ffffff" },
          extraCssText: "box-shadow: 0px 2px 5px 0px rgba(50,107,174,0.19);",
        },
        legend: {
          itemHeight: 12,
          itemWidth: 12,
          icon: "circle",
        },
        // 位置
        grid: {
          left: "2%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: data.categories,
        },
        yAxis: [
          {
            type: "value",
            name: data.series[0].unit,
            axisTick: {
              show: false,
            },
            axisLine: {
              show: false,
            },
            axisLabel: {
              formatter: "{value}",
            },
            min: 0,
          },
        ],
        series: [
          {
            name: data.series[0].name,
            data: data.series[0].data,
            type: "bar",
            barWidth: "16",
            barGap: 7,
            itemStyle: {
              color: "#305ADD",
            },
          },
        ],
      });
      window.addEventListener("resize", function(){
        myChart.resize();
      });
    }
    // 总等效小时的柱状图
    const getEquivalent = (data:any)=> {
      const myChart = echarts.init(document.getElementById("equivalent") as HTMLElement)as echarts.ECharts;
      myChart.setOption({
        // 悬浮提示
        tooltip: {
          show: true,
          trigger: "axis",
          backgroundColor: "#656565",
          textStyle: { color: "#ffffff" },
          extraCssText: "box-shadow: 0px 2px 5px 0px rgba(50,107,174,0.19);",
        },
        legend: {
          itemHeight: 12,
          itemWidth: 12,
          icon: "circle",
        },
        // 位置
        grid: {
          left: "2%",
          right: "4%",
          bottom: "3%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: data.categories,
        },
        yAxis: [
          {
            type: "value",
            name: data.series[0].unit,
            axisTick: {
              show: false,
            },
            axisLine: {
              show: false,
            },
            axisLabel: {
              formatter: "{value}",
            },
            min: 0,
          },
        ],
        series: [
          {
            name: data.series[0].name,
            data: data.series[0].data,
            type: "bar",
            barWidth: "16",
            barGap: 7,
            itemStyle: {
              color: "#305ADD",
            },
          },
        ],
      });
      window.addEventListener("resize", function(){
        myChart.resize();
      });
    }
    const echartsToBase64 = (dom:any)=> {
      try {
        let ech = echarts.getInstanceByDom(dom) as echarts.ECharts;
        let baseUrl = ech.getDataURL({
          type: "png",
          backgroundColor: "#fff",
        });
        return baseUrl;
      } catch (err) {
        return "";
      }
    }
    const getStationOverview = async()=>{
      let res = await getStationOverviews({
        stationId: powerStation.value.id,
        lang: lang.value,
        startDay: timeValue.value[0],
        endDay: timeValue.value[1],
      });
      tableData.value = res.data.viewsList;
      // 展示图表
      if (res.data.uchartsVos) {
        getDailyElectricity(res.data.uchartsVos[0]);
        getEquivalent(res.data.uchartsVos[1]);
      }
    }
    // 导出
    const ExportPDF = async () => {
      const loading =  ElLoading.service({
        lock: true,
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      // 个人业务，获取名字用来当pdf文件名
      let comNameHid = "逆变器"; // 抓取要截图的div的class名  也可以使用ref进行获取
      let target = divExport.value; // pdf背景色
      target.style.background = "#FFFFFF"; // 滚动条置顶，避免截图不全，截图是从当前浏览器看的位置开始截取的
      window.pageYOffset = 0;
      document.documentElement.scrollTop = 0;
      document.body.scrollTop = 0; // pdf工具
      printPdf(comNameHid, target);
      setTimeout(() => {
        loading.close();
      }, 2000);
    }
    const ExportExl = async () => {
      const loading =  ElLoading.service({
        lock: true,
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      let baseUrl = [];
      var img = new Image();
      let canvasID = divExportExl.value;
      await html2canvas(canvasID).then((canvas:any) => {
        img.src = canvas.toDataURL("image/png");
      });
      baseUrl.push(img.src);
      const res = await getAgentExp({
        stationId: powerStation.value.id,
        startDay: timeValue.value[0],
        endDay: timeValue.value[1],
        lang: lang.value,
        base64s: baseUrl,
      });
      let url = window.URL.createObjectURL(
        new Blob([res], { type: "application/vnd.ms-excel" })
      );
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", t("licence.inv_tongji") + ".xls");
      document.body.appendChild(link);
      link.click();
      setTimeout(() => {
        loading.close();
      }, 2000);
    }

    onMounted(()=>{
      const start = new Date(new Date().getTime() - 3600 * 1000 * 24 * 7)
        .toISOString()
        .substring(0, 10)
        .split(".")[0]; //默认开始时间7天前
      const end = new Date(new Date().getTime() - 3600 * 1000 * 24)
        .toISOString()
        .substring(0, 10)
        .split(".")[0]; //默认结束时间1天前
      timeValue.value = [start, end]
      // 获取语言
      if (localStorage.getItem("locale") == "en_US") {
        lang.value = 1;
      } else {
        lang.value = 0;
      }
      // 获取电站信息
      powerStation.value = JSON.parse(localStorage.getItem("powerStation") as string);
      getStationOverview();
    })
</script>
<style scoped lang="scss">
* {
  margin: 0;
  box-sizing: border-box;
  list-style: none;
}

.stationName {
  text-align: center;
  font-weight: 600;
  font-size: 20px;
  margin-top: 30px;
  margin-bottom: 30px;
}

.content {
  background-color: #fff;
  //   height: 100%;
  padding: 20px;
  border-radius: 6px;

  //   时间 导出 标题
  #title {
    font-size: 16px;
    font-family: PingFangSC-Medium, PingFang SC;
    font-weight: 600;
    color: #0e1319;
  }

  .title {
    display: flex;
    justify-content: space-between;
    margin: 20px 0;

    // 查询按钮
    .el-button--primary {
      color: #ffffff;
      background-color: #305add;
      border-color: #305add;
    }

    //导出
    .export {
      width: 90px;
      height: 36px;
      border-radius: 4px;
      border: 1px solid #dddfe6;
      font-size: 14px;
      text-align: center;
      line-height: 36px;
      cursor: pointer;
      margin-left: 20px;
    }
  }

  // 图表的展示
  #echarts {
    margin-top: 30px;

    #title {
      margin-bottom: 30px;
      margin-top: 30px;
    }

    // 日发电量柱状图
    #DailyElectricity {
      height: 560px;
      //   background-color: #f8f9fb;
    }

    // 总等效小时
    #equivalent {
      height: 560px;
    }
  }
}
</style>
